package com.shengde.jinwawaforleader.model.homePage;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.model.personalCenter.activity.PersonalInfoActivity;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.photos.ProImageUpload;
import com.shengde.jinwawaforleader.network.protocolbean.ProShowClickGoodCancle;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadImg;
import com.shengde.jinwawaforleader.utils.CameraActivity;
import com.shengde.jinwawaforleader.utils.DecodeImageUtils;
import com.shengde.jinwawaforleader.utils.LGImgCompressor;
import com.shengde.jinwawaforleader.utils.PhotoUtil;
import com.shengde.jinwawaforleader.utils.PictureUtil;
import com.shengde.jinwawaforleader.utils.ScreenUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import richeditor.ImageUtil;
import richeditor.RichTextEditor;

/**
 * 班级通知发布
 **/

public class SchoolNoteFabuActivity extends Activity implements LGImgCompressor.CompressListener, OnClickListener {
	private static final String TAG = "SchoolNoteFabuActivity";
	private static final int REQUEST_CODE_PICK_IMAGE = 1023;
	private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1022;
	private static final int FINSH = 1;
	ArrayList<String> pic_num = new ArrayList<>(); //用来 装 图片的数量

	private RichTextEditor editor;
	private View btn1, btn2;
	EditText editText;
	public boolean isSelectedInner;//是否只对内部人员发送
	String content = "";
	private TextView textView, fill_add, tv_back;

	private String picturepath = null;
	private String isInner;
	private static final int UPLOAD_SUCCESS = 0;
	private String title;
	private ProgressDialog pd;
	private int curPosition = 1;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case UPLOAD_SUCCESS:
					//解码 表情内容
					String emocontent = "";
					try {
						emocontent = URLEncoder.encode(content, "UTF-8");
					} catch (Exception e) {
						e.printStackTrace();
					}
					showSchoolNews(emocontent);
					editText.setText(null);
					break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_baby_note_fabu);
		initView();
		initData();
		initListener();
	}


	private void initView() {
		btn1 = findViewById(R.id.iv_photo);
		btn2 = findViewById(R.id.iv_take);
		editor = (RichTextEditor) findViewById(R.id.et_fabu_content);
		editText = (EditText) findViewById(R.id.et_fabu_title);
		textView = (TextView) findViewById(R.id.tv_title);
		fill_add = (TextView) findViewById(R.id.fill_add);
		tv_back = (TextView) findViewById(R.id.tv_back);
	}

	private void initData() {
		textView.setText("新建校园公告");
		fill_add.setText("发布");
	}

	private void initListener() {
		tv_back.setOnClickListener(this);
		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		fill_add.setOnClickListener(this);

	}

	/**
	 * 打开相机
	 */
	protected void openCamera() {
		Log.i(TAG, "openCamera: 打开相机");
		Intent intent = new Intent(SchoolNoteFabuActivity.this, CameraActivity.class);
		intent.putExtra("needCut", true);
		startActivityForResult(intent, REQUEST_CODE_CAPTURE_CAMEIA);

	}

	/**
	 * 负责处理编辑数据提交等事宜，请自行实现
	 */
	protected void dealEditData(final List<RichTextEditor.EditData> editList) {
		new AsyncTask<Void, Integer, Void>() {

			@Override
			protected void onPreExecute() {
				pd = new ProgressDialog(SchoolNoteFabuActivity.this);
				pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				pd.setMessage("新公告发布");
				pd.setCancelable(false);
				pd.show();
			}

			@Override
			protected Void doInBackground(Void... params) {
				for (final RichTextEditor.EditData itemData : editList) {
					if (!TextUtils.isEmpty(itemData.inputStr)) {
						content += itemData.inputStr.replaceAll("\n", "<br>") + "<br>";
					} else if (!TextUtils.isEmpty(itemData.imagePath)) {
						try {
							String serverFile = null;
							try {
								serverFile = ProImageUpload.upload(itemData.imagePath);

								String imgUploadUrl = BaseProtocol.IMG_BASE;
								if (curPosition == 1) {
									picturepath = serverFile;
								}
								content += "<img src=" + imgUploadUrl + serverFile + "><br>";
								publishProgress((int) ((curPosition / (float) editList.size()) * 100));
								curPosition++;
							} catch (Exception e) {
								e.printStackTrace();
							} catch (OutOfMemoryError e) {
								e.printStackTrace();
							}
						} catch (Exception e) {
							e.printStackTrace();
						} finally {

						}
					}
				}
				return null;
			}

			@Override
			protected void onProgressUpdate(Integer... progress) {
				pd.setProgress((progress[0]));
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				handler.sendEmptyMessage(UPLOAD_SUCCESS);
			}
		}.execute();
	}

	String path = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK) {
			Uri uri = data.getData();
			path = getRealFilePath(uri);
			Log.e(TAG, "这里的公告: " + path);
			compressImage(path);
		} else if (requestCode == REQUEST_CODE_CAPTURE_CAMEIA && resultCode == RESULT_OK) {
			path = data.getStringExtra("path");
			Log.e(TAG, "你大爷: " + path);
			compressImage(path);
		}
	}

	/**
	 * 压缩图片
	 *
	 * @param path
	 */
	private void compressImage(String path) {
		LGImgCompressor.getInstance(SchoolNoteFabuActivity.this).withListener(SchoolNoteFabuActivity.this).
				starCompress(Uri.fromFile(new File(path)).toString(), 600, 800, 100);

	}

	/**
	 * 添加图片到富文本剪辑器
	 *
	 * @param imagePath
	 */
	private void insertBitmap(String imagePath) {
		pic_num.add(imagePath);
		if (pic_num.size() >9) {
			Toast.makeText(this, "传入的图片不能多于9张", Toast.LENGTH_SHORT).show();
		} else {
			editor.insertImage(imagePath);
		}
	}

	/**
	 * 根据Uri获取图片文件的绝对路径
	 */
	public String getRealFilePath(final Uri uri) {
		if (null == uri) {
			return null;
		}
		final String scheme = uri.getScheme();
		String data = null;
		if (scheme == null) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = getContentResolver().query(uri,
					new String[]{ImageColumns.DATA}, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						data = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return data;
	}

	/**
	 * 网络请求
	 *
	 * @param content
	 */
	private void showSchoolNews(String content) {
		String url = "";
		if (User.isTest) {
			url = BaseProtocol.HOST_BASE_TEST + "/teacher/NoticePublish";
		} else {
			url = BaseProtocol.HOST_BASE + "/teacher/NoticePublish";
		}
		RequestParams params  = BaseProtocol.getRequestParams(url);
		params.addHeader("", "");
		params.addParameter("userid", User.getUserLoginAccount(this));
		params.addParameter("title", title);
		params.addParameter("detail", content);
		params.addParameter("id", User.getSchoolId(this));
		params.addParameter("type", 4);
		params.addParameter("picturepath", picturepath);
		params.addParameter("innerflag", 0);
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				ProShowClickGoodCancle mProShowClickGoodCancle = new Gson().fromJson(result, ProShowClickGoodCancle.class);
				Log.i(TAG, "onSuccess: " + mProShowClickGoodCancle.getCode());
				if (mProShowClickGoodCancle.getCode() == 0) {

					setResult(999);
					pd.dismiss();
					finish();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {

			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {

			}
		});

	}

	@Override
	public void onCompressStart() {
		Log.d(TAG, "onCompressStart");

	}

	@Override
	public void onCompressEnd(LGImgCompressor.CompressResult compressResult) {
		Log.d(TAG, "onCompressEnd outPath:" + compressResult.getOutPath());
		if (compressResult.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)//压缩失败
			return;

		File file = new File(compressResult.getOutPath());
		Bitmap bitmap = null;
		try {
			bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
			float imageFileSize = file.length() / 1024f;
			Log.i(TAG, "onCompressEnd:imageInfo " + "image info width:" + bitmap.getWidth() + " \nheight:" + bitmap.getHeight() +
					" \nsize:" + imageFileSize + "kb" + "\nimagePath:" + file.getAbsolutePath());
			path = file.getAbsolutePath();
			insertBitmap(path);

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.tv_back:
				finish();
				break;
			case R.id.iv_photo:
				// 打开系统相册
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_PICK);
				intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
				break;
			case R.id.iv_take:
				openCamera();
				break;
			case R.id.fill_add:
				List<RichTextEditor.EditData> editList = editor.buildEditData();
				title = editText.getText().toString();
				if (TextUtils.isEmpty(title)) {
					Toast.makeText(SchoolNoteFabuActivity.this, "标题不能为空！", Toast.LENGTH_SHORT).show();
					return;
				}
				isInner = isSelectedInner ? "1" : "2";
				//String s = ProImageUpload.upload(path);

				// 下面的代码可以上传、或者保存，请自行实
				dealEditData(editList);
				break;
		}
	}
}
